'use client'

import React, { useEffect, Suspense } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'
import { useUIStore } from '@/stores/uiStore'

interface NavigationProviderProps {
    children: React.ReactNode
}

function NavigationProviderInner({ children }: NavigationProviderProps) {
    const pathname = usePathname()
    const searchParams = useSearchParams()
    const { navigate, updateBreadcrumbs } = useUIStore()

    // 页面加载时恢复导航状态
    useEffect(() => {
        const fullPath = pathname + (searchParams.toString() ? `?${searchParams.toString()}` : '')

        // 初始化导航状态
        navigate(fullPath)

        // 生成面包屑
        const generateBreadcrumbs = () => {
            const pathSegments = pathname.split('/').filter(Boolean)
            const breadcrumbs = []

            // 首页
            breadcrumbs.push({
                label: '首页',
                path: '/',
                isActive: pathname === '/'
            })

            // 根据路径段生成面包屑
            if (pathSegments.length > 0) {
                pathSegments.forEach((segment, index) => {
                    const isLast = index === pathSegments.length - 1

                    if (segment === 'dataset' && pathSegments[index + 1]) {
                        // 数据集页面
                        const datasetId = pathSegments[index + 1]
                        breadcrumbs.push({
                            label: `数据集 ${datasetId}`,
                            path: `/dataset/${datasetId}`,
                            isActive: isLast || (index === pathSegments.length - 2)
                        })
                    } else if (segment === 'task' && pathSegments[index + 1] && pathSegments[index + 2]) {
                        // 任务页面
                        const datasetId = pathSegments[index + 1]
                        const taskId = pathSegments[index + 2]
                        breadcrumbs.push({
                            label: `任务 ${taskId}`,
                            path: `/task/${datasetId}/${taskId}`,
                            isActive: isLast
                        })
                    }
                })
            }

            return breadcrumbs
        }

        updateBreadcrumbs(generateBreadcrumbs())
    }, [pathname, searchParams, navigate, updateBreadcrumbs])

    // 页面卸载时保存状态
    useEffect(() => {
        const handleBeforeUnload = () => {
            // 保存当前导航状态
            if (typeof window !== 'undefined') {
                const navigationState = {
                    currentPath: pathname,
                    timestamp: Date.now()
                }
                sessionStorage.setItem('navigation_state', JSON.stringify(navigationState))
            }
        }

        window.addEventListener('beforeunload', handleBeforeUnload)
        return () => {
            window.removeEventListener('beforeunload', handleBeforeUnload)
        }
    }, [pathname])

    return <>{children}</>
}

export function NavigationProvider({ children }: NavigationProviderProps) {
    return (
        <Suspense fallback={<div>Loading navigation...</div>}>
            <NavigationProviderInner>{children}</NavigationProviderInner>
        </Suspense>
    )
}